﻿using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Data.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Drawing;
using System.Text;
using System.Web.Mvc;
using System.IO;
using System.Data.Objects;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Web.SessionState;
using System.Web.Security;
using System.Security.Principal;
using FILSTARTUPS_CMS.Helpers;
using FILSTARTUPS_CMS.Models;
using System.Threading;


namespace FILSTARTUPS_CMS.Controllers
{
    public class HomeController : Controller
    {
        FilStartUpsEntities cms_dbconnect = new FilStartUpsEntities();
        Session_Helper session_ = new Session_Helper();

        // dbService db_service = new dbService();
        //
        // GET: /Home/
        public JsonResult ValidateUser(LogOnModel login)
        {
            string password = login.Password == "" || login.Password == null
                            ? Helpers.Session_Helper.HashPassword("hahah") : Helpers.Session_Helper.HashPassword(login.Password.Trim());

            var validate = cms_dbconnect.Users
                                .Where(m => m.Username.Equals(login.UserName.Trim())
                                            && m.Password.Equals(password))
                                                .SingleOrDefault();
            if (validate != null)
            {
                //Create new Cookie

                bool authenticate = Authenticate(validate.Username, validate.roleidFK);

                bool checksession = session_.CheckSession(validate.Username);
                if (checksession == true)
                {
                    bool createsession = session_.CreateSession(validate.Username);
                }
                else
                {
                    session_.UpdateSession(validate.useridPK);
                }
                return Json(true, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(false, JsonRequestBehavior.AllowGet);
            }
        }

        [Authorize]
        public ActionResult Index()
        {
            if (CheckCookie() == false)
            {
                return RedirectToAction("Login");
            }

            int post = 0, drafts = 0;

            var user = cms_dbconnect.Users.Where(u => u.Username.Equals(User.Identity.Name)).SingleOrDefault();

            if (user.roleidFK == 1)
            {
                var userpost = (from p in cms_dbconnect.Post
                                join u in cms_dbconnect.Users
                                on p.useridFK equals u.useridPK
                                join r in cms_dbconnect.RoutingType
                                on p.routingidFK equals r.routingidPK
                                orderby p.postidPK descending
                                select new PostGrid
                                {
                                    posttitle = p.posttitle,
                                    datecreated = p.datecreated,
                                    viewtype = r.routingname,
                                    postidPK = p.postidPK

                                }).ToList();

                foreach (var item in userpost)
                {
                    if (item.viewtype == "Posting")
                    {
                        post += 1;
                    }
                    else
                    {
                        drafts += 1;
                    }
                }
                ViewBag.Posting = post;
                ViewBag.Drafts = drafts;
                ViewData["routing"] = cms_dbconnect.RoutingType.OrderBy(r => r.routingidPK).ToList();
                return View(userpost);
            }
            else
            {
                var userpost = (from p in cms_dbconnect.Post
                                join u in cms_dbconnect.Users
                                on p.useridFK equals u.useridPK
                                join r in cms_dbconnect.RoutingType
                                on p.routingidFK equals r.routingidPK
                                where u.Username.Contains(User.Identity.Name)
                                select new PostGrid
                                {
                                    posttitle = p.posttitle,
                                    datecreated = p.datecreated,
                                    viewtype = r.routingname,
                                    postidPK = p.postidPK
                                }).ToList();

                foreach (var item in userpost)
                {
                    if (item.viewtype == "Posting")
                    {
                        post += 1;
                    }
                    else
                    {
                        drafts += 1;
                    }
                }

                ViewBag.Posting = post;
                ViewBag.Drafts = drafts;
                ViewData["routing"] = cms_dbconnect.RoutingType.OrderBy(r => r.routingidPK).ToList();

                return View(userpost);
            }
        }

        //Filtering of Data 
        public PartialViewResult Filter(int routing)
        {
            var user = cms_dbconnect.Users.Where(u => u.Username.Equals(User.Identity.Name)).SingleOrDefault();
            //Check if(Role = admin)
            //Return all of the query
            if (user.roleidFK == 1)
            {
                var userpost = (from p in cms_dbconnect.Post
                                join u in cms_dbconnect.Users
                                on p.useridFK equals u.useridPK
                                join r in cms_dbconnect.RoutingType
                                on p.routingidFK equals r.routingidPK
                                where p.routingidFK.Equals(routing)
                                select new PostGrid
                                {
                                    posttitle = p.posttitle,
                                    datecreated = p.datecreated,
                                    viewtype = r.routingname,
                                    postidPK = p.postidPK
                                }).ToList();

                return PartialView("_PostUser", userpost);
            }
            else // Specified User Post
            {
                var userpost = (from p in cms_dbconnect.Post
                                join u in cms_dbconnect.Users
                                on p.useridFK equals u.useridPK
                                join r in cms_dbconnect.RoutingType
                                on p.routingidFK equals r.routingidPK
                                where u.Username.Contains(User.Identity.Name)
                                && p.routingidFK.Equals(routing)
                                select new PostGrid
                                {
                                    posttitle = p.posttitle,
                                    datecreated = p.datecreated,
                                    viewtype = r.routingname,
                                    postidPK = p.postidPK
                                }).ToList();

                return PartialView("_PostUser", userpost);
            }
        }

        public ActionResult Login()
        {
            //if User is Authenticated
            //if (User.Identity.IsAuthenticated)
            //{
            //Check Cookie Value
            //if Cookie Value is set==>Redirect To Index
            if (CheckCookie() == true)
            {
                return RedirectToAction("Index");
            }
            //  return RedirectToAction("Index");
            // }
            else
            {
                return View();
            }
        }



        [HttpPost]
        public ActionResult Login(FormCollection form, LogOnModel login, string returnUrl)
        {

            //Check data in database
            var user = (from u in cms_dbconnect.Users
                        where u.Username.Equals(login.UserName) &&
                        u.Password.Equals(login.Password) &&
                         u.UserStatus == true
                        select u).SingleOrDefault();

            if (user != null)
            {
                //Session and FormsAuthentication

                //Check Session if flag == true validate user
                bool check = session_.CheckSession(user.Username);
                if (check == false)
                {
                    return View();
                }



                //Create new Cookie
                bool authenticate = Authenticate(user.Username, user.roleidFK);

                //Create a new session in database
                bool session_user = session_.CreateSession(user.Username);

                if (authenticate == true && session_user == true)
                {
                    //Set Session["role"]
                    var role = cms_dbconnect.Roles.Where(r => r.roleidPK == user.roleidFK).SingleOrDefault();
                    Session["role"] = role.Rolename;
                    return RedirectToAction("Index");
                }
                else//Return Error
                {
                    return View();
                }

            }
            else //Error Msg
            {
                TempData["message"] = string.Format("Invalid Username or Password");
                return View();
            }

        }

        [Authorize]
        public ActionResult Logout()
        {
            //Session Flag Update Database
            session_.AbandonSession(User.Identity.Name);

            FormsAuthentication.SignOut();
            Session.Abandon();
           
            // clear authentication cookie
            HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
            cookie1.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie1);

            // clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
            HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
            cookie2.Expires = DateTime.Now.AddYears(-1);
            Response.Cookies.Add(cookie2);


            // Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now.AddYears(-1);
            //Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
            //  Request.Cookies.Remove(FormsAuthentication.FormsCookieName);
            //foreach (var cookie in Request.Cookies.AllKeys)
            //{
            //    Request.Cookies.Remove(cookie);
            // }
            //foreach (var cookie in Response.Cookies.AllKeys)
            //{
            //   Response.Cookies.Remove(cookie);
            //}

            //Set Session Flag == false;
            // bool abandonsession = session_.AbandonSession(User.Identity.Name);
            //if (abandonsession == true)
            // {
            return RedirectToAction("Login");
            // }
            //else
            // {
            //    return RedirectToAction("Index");
            // }
        }

        //Check Cookie
        //if return True Cookie value==not null
        //else Cookie value == null
        private bool CheckCookie()
        {
            //Check If Cookie is still alive
            string cookieName = "FilStartUps";
            HttpCookie cookie = HttpContext.Request.Cookies[cookieName];
            if (cookie != null && cookie.Value != String.Empty)
            {
                FormsAuthenticationTicket tik = FormsAuthentication.Decrypt(cookie.Value);
                if (tik != null)
                {
                    FormsIdentity id = new FormsIdentity(tik);
                    //Retrive data from database
                    var cookie_check = (from u in cms_dbconnect.Users
                                        join r in cms_dbconnect.Roles
                                        on u.roleidFK equals r.roleidPK
                                        where u.Username.Equals(id.Name)
                                        select r).SingleOrDefault();
                    //Check if the retrieve data is != null
                    //if not set the Session["role"] to the rolename
                    if (cookie_check != null)
                    {
                        Session["role"] = cookie_check.Rolename;
                    }

                    return true;

                }
                //No Data in Cookie
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }

        }
        private bool Authenticate(string username, int roleidPK)
        {

            string role;
            if (roleidPK == 1)
            {
                role = "Administrator";
            }
            else
            {
                role = "User";
            }
            //   string cookiename = "FilStartUps";

            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                1,
                username,
                DateTime.Now,
                DateTime.Now.AddHours(24),
                false,
                role,
                FormsAuthentication.FormsCookiePath);

            string hash = FormsAuthentication.Encrypt(ticket);

            //Cookie Name
            HttpCookie cookie = new HttpCookie(
                FormsAuthentication.FormsCookieName,
                hash);

            if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;

            Response.Cookies.Add(cookie);
      
            return true;
        }
    }



    /**************
    
    public class dbService
    {
        FilStartUpsEntities cms_dbconnect = new FilStartUpsEntities();

        public IQueryable<Role> GetUserRole(int userID)
        {
            return (from r in cms_dbconnect.Roles
                    join
                        u in cms_dbconnect.Users on
                        r.roleidPK equals u.roleidFK
                    select r);
        }

        public IEnumerable<User> GetUsername(string username, string password)
        {
            return (from u in cms_dbconnect.Users
                        .Where(us=>us.Username==username && us.Password == password) 
                    select u);
        }
        public bool LogOn(string username, string password)
        {
            try
            {
                var userid = GetUsername(username, password);
                var rolesIQueryable = GetUserRole(Convert.ToInt32(userid.Select(x => x.useridPK).Single()));
                string roles = "";
                foreach (var role in rolesIQueryable)
                {
                    roles += role.Rolename + ",";
                }
                roles.Substring(0, roles.Length - 2);

                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                    1,
                    username,
                    DateTime.Now,
                    DateTime.Now.AddMinutes(30),
                    true,
                    roles,
                    FormsAuthentication.FormsCookiePath);

                string hash = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
                                                           hash);
                return true;
            }
            catch
            {
                return false;
            }
        }

    } PRIVATE *************/


}
